//
//  PzCoinCtrl.swift
//  Pz
//
//  Created by 蓝鳍互娱 on 2024/6/26.
//

import Foundation
import UIKit
class PzCoinCtrl: UIViewController {
    var allCoinNum = 3
    var currentCoinNum = 0
    var zCoinNum = 0
    var fCoinNum = 0
    var defAutoNum:String? = UserDefaults.standard.value(forKey: "pzDefAutoNum") as? String
    var defVoiceOpen:String? = UserDefaults.standard.value(forKey: "pzDefVoiceOpen") as? String

    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationController?.navigationBar.isHidden = true
        view.backgroundColor = .clear
        creatSubView()
    }
    lazy var coinBgImgView: UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "pzHomeBg")
        return imageView
    }()
    lazy var coinNavBackBtn: UIButton = {
        let btn = UIButton()
        btn.addTarget(self, action: #selector(meNavBack), for: .touchUpInside)
        btn.setBackgroundImage(UIImage(named: "pzNavBackIcon"), for: .normal)
        return btn
    }()
    lazy var coinNavTitleLab: UILabel = {
        let lab = UILabel()
        lab.text = "抛硬币"
        lab.font = UIFont.systemFont(ofSize: 34.fitScale(), weight: .regular)
        lab.textColor = UIColor(hex:0xFFFFFF)
        return lab
    }()
    lazy var coinSetBtn: UIButton = {
        let btn = UIButton()
        btn.addTarget(self, action: #selector(homeSet), for: .touchUpInside)
        btn.setBackgroundImage(UIImage(named: "pzHomeSetIcon"), for: .normal)
        return btn
    }()
    lazy var zCoinNumView: PzCoinNumView = {
        let view = PzCoinNumView()
        view.coinNumType = "1"
        return view
    }()
    lazy var fCoinNumView: PzCoinNumView = {
        let view = PzCoinNumView()
        view.coinNumType = "2"
        return view
    }()
    lazy var coinImgView: UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "pzCoinYes")
        return imageView
    }()
    lazy var coinStartBtn: UIButton = {
        let btn = UIButton()
        btn.addTarget(self, action: #selector(coinBeginStart), for: .touchUpInside)
        btn.setBackgroundImage(UIImage(named: "pzCoinStart"), for: .normal)
        return btn
    }()
    lazy var coinCountLab: UILabel = {
        let lab = UILabel()
        lab.font = UIFont.systemFont(ofSize: 32.fitScale(), weight: .regular)
        lab.textColor = UIColor(hex:0xFFFFFF)
        lab.text = String(currentCoinNum) + "/" + String(allCoinNum)
        lab.textAlignment = .center
        return lab
    }()
    
    func creatSubView(){
        let defNum:String? = UserDefaults.standard.value(forKey: "pzDefNum") as? String
        allCoinNum = Int(defNum ?? "3")!
        
        self.view.addSubview(coinBgImgView)
        self.view.addSubview(coinNavBackBtn)
        self.view.addSubview(coinNavTitleLab)
        self.view.addSubview(coinSetBtn)
        self.view.addSubview(zCoinNumView)
        self.view.addSubview(fCoinNumView)
        self.view.addSubview(coinImgView)
        self.view.addSubview(coinCountLab)
        self.view.addSubview(coinStartBtn)
        
        coinBgImgView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        coinNavBackBtn.snp.makeConstraints { make in
            make.left.equalTo(24.fitScale())
            make.top.equalTo(PzPublicConst.ScreenTopSpaceHeight + 12.fitScale())
            make.width.height.equalTo(64.fitScale())
        }
        coinNavTitleLab.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalTo(coinNavBackBtn)
            make.height.equalTo(50.fitScale())
        }
        coinSetBtn.snp.makeConstraints { make in
            make.right.equalTo(-24.fitScale())
            make.top.equalTo(PzPublicConst.ScreenTopSpaceHeight + 25.fitScale())
            make.width.height.equalTo(44.fitScale())
        }
        zCoinNumView.snp.makeConstraints { make in
            make.left.equalTo(28.fitScale())
            make.top.equalTo(PzPublicConst.ScreenTopSpaceHeight + 124.fitScale())
            make.height.equalTo(218.fitScale())
        }
        fCoinNumView.snp.makeConstraints { make in
            make.left.equalTo(zCoinNumView.snp.right).offset(58.fitScale())
            make.right.equalTo(-28.fitScale())
            make.top.equalTo(zCoinNumView)
            make.height.equalTo(zCoinNumView)
            make.width.equalTo(zCoinNumView)
        }
        coinImgView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(fCoinNumView.snp.bottom).offset(154.fitScale())
            make.height.equalTo(424.fitScale())
            make.width.equalTo(428.fitScale())
        }
        coinStartBtn.snp.makeConstraints { make in
            make.left.equalTo(24.fitScale())
            make.right.equalTo(-24.fitScale())
            make.bottom.equalTo(-76.fitScale())
            make.height.equalTo(80.fitScale())
        }
        coinCountLab.snp.makeConstraints { make in
            make.left.equalTo(0.fitScale())
            make.right.equalTo(-0.fitScale())
            make.bottom.equalTo(coinStartBtn.snp.top).offset(-19.fitScale())
            make.height.equalTo(50.fitScale())
        }
//        let all = UserDefaults.standard.object(forKey: "pzDefNum")
//        allCoinNum = UserDefaults.standard.object(forKey: "pzDefNum") as! Int
    }
    @objc func coinBeginStart(){
        if currentCoinNum >= allCoinNum{
            currentCoinNum = 0
            zCoinNum = 0
            fCoinNum = 0
            zCoinNumView.coinNum = String(zCoinNum)
            fCoinNumView.coinNum = String(fCoinNum)
        }
        coinCountLab.text = String(currentCoinNum) + "/" + String(allCoinNum)
        coinStart()
    }
    @objc func coinStart(){
        let defVoiceOpen:String? = UserDefaults.standard.value(forKey: "pzDefVoiceOpen") as? String
        if (defVoiceOpen == "2"){
            playAudio()
        }
        
        self.coinImgView.layer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
        self.coinImgView.layer.zPosition = 214
        
        let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.x")
        rotationAnimation.fromValue = 0.0
        rotationAnimation.toValue = CGFloat.pi
        rotationAnimation.duration = 0.3
        rotationAnimation.repeatCount = 10
        rotationAnimation.delegate = self
        self.coinImgView.layer.add(rotationAnimation, forKey: "rotationAnimation")
        startChangeImg()
    }
    @objc func startChangeImg(){
        let pzCoinYesImg = UIImage(named: "pzCoinYes")!
        let pzCoinNoImg = UIImage(named: "pzCoinNo")!
        var mages = [UIImage]()
        mages.append(pzCoinYesImg)
        mages.append(pzCoinNoImg)
        self.coinImgView.animationImages = mages
        self.coinImgView.animationDuration = 0.3
        self.coinImgView.animationRepeatCount = 10
        self.coinImgView .startAnimating()
    }
    @objc func homeSet(){
        self.coinImgView.layer.zPosition = 0
        PzDefCoinNumView.showDefCoinNumView(keyView: self.view) {
            let defNum:String? = UserDefaults.standard.value(forKey: "pzDefNum") as? String
            self.allCoinNum = Int(defNum ?? "3")!
            self.currentCoinNum = 0
            self.coinCountLab.text = String(self.currentCoinNum) + "/" + String(self.allCoinNum)
            self.zCoinNum = 0
            self.fCoinNum = 0
            self.zCoinNumView.coinNum = String(self.zCoinNum)
            self.fCoinNumView.coinNum = String(self.fCoinNum)
        };
    }
    var audioPlayer:AVAudioPlayer?
    func playAudio() {
        if let audioPath = Bundle.main.path(forResource: "fish", ofType: "mp3") {
            let audioUrl = URL(fileURLWithPath: audioPath)
            
            do {
                audioPlayer = try AVAudioPlayer(contentsOf: audioUrl)
                audioPlayer?.play()
            } catch {
                print("Error initializing AVAudioPlayer: \(error.localizedDescription)")
            }
        } else {
            print("Audio file not found")
        }
    }
    @objc func meNavBack(){
        self.navigationController?.popViewController(animated: true)
    }
}
extension PzCoinCtrl:CAAnimationDelegate{
    func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
        let randomBool = Int(arc4random_uniform(2))
        if randomBool != 1 {
            self.coinImgView.image = UIImage(named: "pzCoinYes")
            zCoinNum = zCoinNum + 1
        } else {
            self.coinImgView.image = UIImage(named: "pzCoinNo")
            fCoinNum = fCoinNum + 1
        }
        zCoinNumView.coinNum = String(zCoinNum)
        fCoinNumView.coinNum = String(fCoinNum)
        currentCoinNum = currentCoinNum + 1
        coinCountLab.text = String(currentCoinNum) + "/" + String(allCoinNum)

        if currentCoinNum < allCoinNum{
            let defAutoNum:String? = UserDefaults.standard.value(forKey: "pzDefAutoNum") as? String
            if (defAutoNum == "2"){
                self.perform(#selector(coinBeginStart), with: self, afterDelay: 0.5)
            }
        }
    }
}
